package com.softaria.spkiller.classfinder;

import java.io.File;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


public class ClassFinder {
	
	 private static final String CLASS_EXTENSION = ".class";
	private static final String[] ZIP_FILE_TYPES 
     = new String[] {".zip", ".jar"} ; 
	
	public void traverse(String[] pathesToFoldersOrJars,ClassCollector collector) throws IOException {

		for(String path:pathesToFoldersOrJars) {
			File file = new File(path);
			
			processFile(file,collector);
		}
	}
	
	private void processFile(File file, ClassCollector collector) throws IOException {
		if(file.isDirectory()) {
			File[] files = file.listFiles();
			
			for(File f:files) {
				processFile(f,collector);
			}
		}
		else {
			if(file.getAbsolutePath().endsWith(CLASS_EXTENSION)) {
				collector.collect(file.getAbsolutePath(), new FileInputStreamGetter(file));
			}
			else {
				if(isZipFile(file)) {
					processZipFile(new ZipFile(file),collector);
				}
			}
		}
		
	}
	
	
	 private void processZipFile(ZipFile zipFile, ClassCollector collector) throws IOException {
		Enumeration<? extends ZipEntry> entries = zipFile.entries();
		
		while(entries.hasMoreElements()) {
			ZipEntry entry = entries.nextElement();
			
			if((!entry.isDirectory())&&(entry.getName().toLowerCase().endsWith(CLASS_EXTENSION))) { 
				collector.collect(entry.getName(), new ZipInputStreamGetter(zipFile,entry));
			}
			
			
		}
		
	}

	private static boolean isZipFile(File file) 
	  {
	    boolean result = false;
	    String name = file.getName().toLowerCase();
	    
	    for (int i = 0; i < ZIP_FILE_TYPES.length; i++) 
	    {
	      if (name.endsWith(ZIP_FILE_TYPES[i]))
	      {
	        result = true;
	        break;
	      }
	    }
	    return result;
	  }
	
}
